package com.cscec.omega.service;

import com.cscec.omega.dao.ApiDao;
import com.cscec.omega.entity.APIEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class APIService {

    private static Logger logger = LoggerFactory.getLogger(APIService.class);

    @Autowired
    private ApiDao apiDao;

    /**
     * 保存
     * @param apiEntity
     * @return
     */
    public APIEntity save(APIEntity apiEntity){
        try{
            apiEntity = apiDao.save(apiEntity);
        }catch (Exception e) {
            logger.error("save error: ", e);
        }
        return apiEntity;
    }

    /**
     * 查询
     * @return
     */
    public List<APIEntity> findAll(){
        return apiDao.findAll();
    }

    /**
     * 条件查询
     * @param apiEntity
     * @return
     */
    public Page<APIEntity> find(APIEntity apiEntity, Integer pageSize, Integer page){
        Pageable pageable = PageRequest.of(page,pageSize);
        Page<APIEntity> result = apiDao.findAll(Example.of(apiEntity), pageable);
        return result;
    }

    public List<APIEntity> find(APIEntity apiEntity){
        List<APIEntity> result = apiDao.findAll(Example.of(apiEntity), Sort.by(Sort.Direction.DESC, "id"));
        return result;
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    public APIEntity findById(Integer id){
        Optional<APIEntity> optional = apiDao.findById(id);
        if (StringUtils.isEmpty(optional)) {
            return new APIEntity();
        }
        return optional.get();
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Integer id) {
        apiDao.deleteById(id);
    }
}
